package com.wanghui.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wanghui.reggie.common.CustomException;
import com.wanghui.reggie.dto.SetmealDto;
import com.wanghui.reggie.entity.Setmeal;
import com.wanghui.reggie.entity.SetmealDish;
import com.wanghui.reggie.mapper.SetmealMapper;
import com.wanghui.reggie.service.SetmealDishService;
import com.wanghui.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐，同时向套餐表和套餐关联表添加数据
     *
     * @param setmealDto
     */
    @Override
    @Transactional
    public void saveWithSetmeal(SetmealDto setmealDto) {
        //向套餐表中添加数据——套餐基本信息
        this.save(setmealDto);

        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes();    //获取套餐和菜品的关联信息
        //由于该关联信息中缺少setmeal_id,所以需要我们手动添加上
        setmealDishList.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        //向套餐关联表添加数据——套餐和菜品的关联数据
        setmealDishService.saveBatch(setmealDishList);
    }

    /**
     * 删除套餐，同时删除套餐表和套餐关联表中的数据
     * @param ids
     */
    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        //查询套餐表中对应套餐是否处于售卖转态(这里查询处于售卖转态的套餐)
        //对应sql：select count(*) from setmeal where id in (...) and status = 1;
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId, ids);
        queryWrapper.eq(Setmeal::getStatus, 1);
        int count = this.count(queryWrapper);
        //如果处于售卖转态，则抛出异常
        if (count > 0) {
            //大于0表示当前要删除的套餐id中存在售卖状态的套餐，所以不能删除__抛出异常
            throw new CustomException("套餐正在售卖中，不能删除");
        }

        //如果可以删除，则先删除套餐表中的数据
        this.removeByIds(ids);

        //在删除套餐关联表中的数据
        //对应sql：delete from setmeal_dish where setmeal_id in (...);
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.in(SetmealDish::getSetmealId, ids);
        setmealDishService.remove(lambdaQueryWrapper);
    }
}
